package vip.liux.gateway.consts;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;

public interface GlobalConstant {
    ObjectMapper OM = new ObjectMapper().registerModule(new JavaTimeModule());

    static String writeValueAsString(Object obj) {
        if (obj == null) {
            return null;
        }
        try {
            return OM.writeValueAsString(obj);
        } catch (Exception e) {
            return obj.toString();
        }
    }

    static byte[] writeValueAsBytes(Object obj) {
        if (obj == null) {
            return null;
        }
        try {
            return OM.writeValueAsBytes(obj);
        } catch (Exception e) {
            throw new RuntimeException("Failed to serialize object to bytes", e);
        }
    }

    static <T> T readValue(String content, TypeReference<T> valueTypeRef) {
        try {
            return OM.readValue(content, valueTypeRef);
        } catch (Exception e) {
            throw new RuntimeException("Failed to deserialize JSON to object", e);
        }
    }

    static <T> T readValue(String content, Class<T> valueType) {
        try {
            return OM.readValue(content, valueType);
        } catch (Exception e) {
            throw new RuntimeException("Failed to deserialize JSON to object", e);
        }
    }
}
